#!/usr/bin/env python3
"""
一键启动：python3 server.py
API:
POST /save  {"text":"买牛奶"}
GET  /list  → [{"id":1,"text":"...","time":"2025-09-14 21:00:00"},...]
"""
import sqlite3, json, time, sys, os
from http.server import HTTPServer, BaseHTTPRequestHandler

DB_FILE = os.path.join(os.path.dirname(__file__), 'notes.db')

def init_db():
    conn = sqlite3.connect(DB_FILE)
    conn.execute('''
        CREATE TABLE IF NOT EXISTS notes(
          id   INTEGER PRIMARY KEY AUTOINCREMENT,
          text TEXT NOT NULL,
          time TEXT NOT NULL
        );
    ''')
    # 预插一条示例数据
    cur = conn.execute('SELECT COUNT(*) FROM notes').fetchone()[0]
    if cur == 0:
        conn.execute('INSERT INTO notes(text,time) VALUES(?,?)',
                     ('Hello, 第一条随手记！', time.strftime('%Y-%m-%d %H:%M:%S')))
    conn.commit(); conn.close()

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/save':
            length = int(self.headers['Content-Length'])
            body = self.rfile.read(length).decode()
            try:
                text = json.loads(body)['text']
            except Exception:
                self.send_error(400, 'bad json'); return
            conn = sqlite3.connect(DB_FILE)
            conn.execute('INSERT INTO notes(text,time) VALUES(?,?)',
                         (text, time.strftime('%Y-%m-%d %H:%M:%S')))
            conn.commit(); conn.close()
            self.send_response(200); self.end_headers(); self.wfile.write(b'{"ok":true}')
        else:
            self.send_error(404)

    def do_GET(self):
        if self.path == '/list':
            conn = sqlite3.connect(DB_FILE)
            rows = conn.execute('SELECT id,text,time FROM notes ORDER BY id DESC').fetchall()
            conn.close()
            notes = [{'id':r[0],'text':r[1],'time':r[2]} for r in rows]
            self.send_response(200)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(notes, ensure_ascii=False).encode())
        elif self.path == '/' or self.path == '/note.html':
            # 直接托管 note.html
            html_path = os.path.join(os.path.dirname(__file__), 'note.html')
            with open(html_path, 'rb') as f:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html; charset=utf-8')
                self.end_headers()
                self.wfile.write(f.read())
        else:
            self.send_error(404)

if __name__ == '__main__':
    init_db()
    PORT = 8080
    print(f"SQLite API & note.html locked on {PORT}")
    HTTPServer(('0.0.0.0', PORT), Handler).serve_forever()